package com.dengyuanke.admin.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.dengyuanke.common.result.JsonResult;
import com.dengyuanke.entity.Admin;
import com.dengyuanke.service.IAdminService;
import com.dengyuanke.utils.CryptoUtils;
import com.dengyuanke.utils.jwt.JWT;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import static com.dengyuanke.common.result.JsonResult.renderFail;
import static com.dengyuanke.common.result.JsonResult.renderSuccess;

/**
 * Created by dengyuanke on 2017/11/9.
 */
@Api(tags = "管理员登录相关API")
@RestController
public class LoginController {

    @Autowired
    private IAdminService adminService;

    /**
     * 登录
     * @return
     */
    @ApiOperation("管理员登录接口")
    @PostMapping("/login")
    public JsonResult login(@ApiParam(value = "用户名",name = "username",required = true)String username,
                            @ApiParam(value = "密码",name = "password",required = true)String password){
        password = CryptoUtils.encodeMD5(password);
        Admin admin = adminService.selectOne(new EntityWrapper<Admin>().eq("username", username).eq("password", password));
        if(admin!=null){
            Map<String , Object> payload=new HashMap<String, Object>(16);
            Date date=new Date();
            admin.setPassword(null);
            payload.put("user", admin);
            //生成时间
            payload.put("iat", date.getTime());
            //15分钟过期
            payload.put("ext",date.getTime()+15*60*1000);
            String token= JWT.createToken(payload);
            return renderSuccess((Object) token);
        }
        return  renderFail("用户名或密码错误");
    }

}
